﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using TaskHub.LocalStorage;

namespace TaskHub
{
    public partial class Login : PhoneApplicationPage
    {
        private ucProgress _Progress;
        private ucProgress Progress
        {
            get
            {
                if (_Progress == null)
                {
                    _Progress = new ucProgress();
                }
                return _Progress;
            }
        }

        public Login()
        {
            InitializeComponent();
        }

        private void login(object sender, EventArgs e)
        {
            try
            {
                this.Focus();
                this.txtErrorMessage.Text = "";
                Progress.Show ();
                wsAccount.AccountSoapClient ws = new wsAccount.AccountSoapClient();
                ws.AuthenticateAccountCompleted += new EventHandler<wsAccount.AuthenticateAccountCompletedEventArgs>(ws_AuthenticateAccountCompleted);
                ws.AuthenticateAccountAsync(this.txtEmail.Text.ToString(), this.txtPwd.Password.ToString());
            }
            catch (Exception)
            {
                throw;
            }
        }

        void ws_AuthenticateAccountCompleted (object sender, wsAccount.AuthenticateAccountCompletedEventArgs e)
        {
            uint iOwner;

            Progress.Hide();

            if (e.Error == null)
            {
                iOwner = e.Result;
                if (iOwner > 0)
                {
                    IsolatedStorageDAO.setMyId(Convert.ToInt32(iOwner.ToString()));
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                }
                else
                {
                    this.txtErrorMessage.Foreground = new SolidColorBrush(Colors.Red);
                    this.txtErrorMessage.Text = "Could not connect to your TaskHub account.";
                }
            }
            else
            {
                this.txtErrorMessage.Foreground = new SolidColorBrush(Colors.Red);
                this.txtErrorMessage.Text = "Could not connect to your TaskHub account.";
            }
        }

        private void cancel(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void register_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                NavigationService.Navigate(new Uri("/Register.xaml", UriKind.Relative));
            }
            catch (Exception)
            {
                
                throw;
            }
        }
    }
}